package com.mop.app.global.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * @description：将金额格式化成每三位以.分隔的字符串
 * @author：liqiang
 * @date：2019-08-07 09:31
 * @warning：本内容仅限于杭州阿拉丁信息科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
@JsonComponent
public class BigDecimalSerializer extends JsonSerializer<BigDecimal> {
    /**
     * Method that can be called to ask implementation to serialize
     * values of type this serializer handles.
     *
     * @param value       Value to serialize; can <b>not</b> be null.
     * @param gen         Generator used to output resulting Json content
     * @param serializers Provider that can be used to get serializers for
     */
    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null || value.compareTo(BigDecimal.ONE) < 0) {
            gen.writeNumber(value);
            return;
        }
        NumberFormat numberFormat = new DecimalFormat("#,###");
        String formatValue = numberFormat.format(value);
        formatValue = formatValue.replace(",", ".");
        gen.writeString(formatValue);
    }
}
